import path from "node:path"
import { globSync } from "glob"
import inquirer from "inquirer"
import fs from "node:fs"

import transform from "./transform.js"

const projectRoot = process.cwd()

/**
 * 确认项目的目录
 */
const ensureProject = async () => {
  try {
    let answers = await inquirer.prompt([
      {
        type: "confirm",
        name: "root",
        message: "项目运行根目录: " + " " + projectRoot,
        default: true
      },
      {
        type: "input",
        name: "route",
        message: "路由路径",
        validate(vlaue: string | null) {
          if (!vlaue) return "请输入项目路由地址"

          // 验证路由文件是否存在
          const p = path.resolve(projectRoot, vlaue)

          try {
            fs.statSync(p)
            return true
          } catch (error) {
            return "路径不存在"
          }
        }
      }
    ])

    if (!answers.root) return false

    return answers.route
  } catch (error) {
    return false
  }
}

/**
 * 拿到所有的路由信息
 */
const getFiles = (p: string): Array<string> => {
  // 如果是文件，就直接读取这个文件，如果是目录，就拿到整个目录里面所有的js文件
  try {
    const stats = fs.statSync(p)

    if (stats.isDirectory()) {
      const jsFiles = globSync(`${projectRoot}/${p}/**/*.js`, {
        // 返回绝对地址
        absolute: true
      })

      return jsFiles
    } else {
      // 文件
      return [path.resolve(projectRoot, p)]
    }
  } catch (error) {
    return []
  }
}

export default async () => {
  let routesPath = await ensureProject()

  if (!routesPath) {
    console.log("信息验证失败 或放弃")
    console.log(routesPath)
    return
  }

  const files = getFiles(routesPath)

  console.log("拿到的所有路由文件：", `【${files.length}】个`)

  console.log(files)

  transform(files)
}
